from .base import Handler
from event_engine.event_type import *
from event_engine.event import Event
from event_engine.engine import EventEngine
from models.task import *
from models.ip_pool import IP
import libs.http as http

# 任务类型映射事件类型
TASK_TO_EVENT = {
    TYPE_SECONDARY_DISTRICT: EVENT_SECONDARY_DISTRICT,
    TYPE_SECONDARY_CIRCLE: EVENT_SECONDARY_CIRCLE,
    TYPE_SECONDARY_LIST: EVENT_SECONDARY_LIST,
    TYPE_RENT_DISTRICT: EVENT_RENT_DISTRICT,
    TYPE_RENT_CIRCLE: EVENT_RENT_CIRCLE,
    TYPE_RENT_LIST: EVENT_RENT_LIST,
}


class DownloadHandler(Handler):
    """
    下载处理器
    """

    def process(self, event: Event, engine: EventEngine) -> None:
        task: Task = event.data["task"]
        ip: IP = event.data["ip"]
        status_code, text = http.get(task.url, task.referer, ip.get_addr())
        ip.use()

        if 200 != status_code:
            print("http status:", status_code, task.url)
        else:
            event.data["html"] = text

            # 用任务类型转为事件类型
            event_type = TASK_TO_EVENT[task.type]
            engine.put(Event(event_type, event.data))
